//
//  AddGoldViewController.swift
//  Box
//
//  Created by mn on 2025/4/3.
//

import UIKit
import AlipaySDK
class AddGoldViewController: BaseViewController {

    lazy var contentView = UIView(frame: CGRectMake(0, 0, view.bounds.width, view.bounds.height))
    
    private let tipTitleLabel: UILabel = {
        let label = UILabel()
        label.text = "温馨提示："
        label.textColor = UIColor(hex: "#333333")
        label.font = .systemFont(ofSize: 15)
        return label
    }()
    
    private let tipContentLabel: UILabel = {
        let label = UILabel()
        label.text = """
        1.充值的金币可在商城兑换商品；
        
        2.充值的金币不会过期，支付后剩余的金币不支持赠送，不支持提现；
        
        3.未成年人消费需事先取得家人或法定监护人的陪同及监督下进行消费；
        
        4.充值前请您仔细阅读《服务协议》，成功充值即代表您对本协议无异议。
        """
        label.textColor = UIColor(hex: "#999999")
        label.font = .systemFont(ofSize: 12)
        label.numberOfLines = 0
        return label
    }()
    private let tableView = UITableView()

    lazy var button: InsetBorderButton = {
        let button = InsetBorderButton(type: .custom)
        button.setTitle("提交充值订单", for: .normal)
        button.setTitleColor(.fromHex("#CAFE67"), for: .normal)
        button.layer.cornerRadius = 7.5
        button.titleLabel?.font = .systemFont(ofSize: 16)
        button.backgroundColor = .black
        button.borderColor = .white
        button.addAction { [weak self] in
            self?.createPayOrder()
        }
        return button
    }()
    let mineGoldView = MineGoldView()
    let selectGoldView = SelectGoldView()
    let inputGoldCountView = InputGoldCountView()
    
    func createPayOrder() {
        var amount: Int? = nil
        if selectGoldView.selectIndex < 0{
            amount = (Int(inputGoldCountView.textField.text ?? "") ?? 0) * 100
        }else{
            amount = selectGoldView.amount
        }
//        debugPrint(amount)
//        return
#if DEBUG
        amount = 1
#endif
        guard let amount  else { return }
        APIService.request(api: .createPayOrder(amount: amount)) {
            /*[weak self] */(result,response) in
            if result.success ,let payInfoData: PayInfoData = Decoder.data(response){
                debugPrint(payInfoData.data)
                AlipaySDK.defaultService()?.payOrder(payInfoData.data.result,
                                                     fromScheme: payInfoData.data.sign) {
                    resultDic in
                    print("支付结果: \(String(describing: resultDic))")
                }
            }
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        guard let user = UserManager.shared.currentUser else {
            mineGoldView.bottomLabel.text = "0.00"
            return
        }
        mineGoldView.bottomLabel.text = String(format: "%.2f", Float(user.balance) * 0.01)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "金币充值"
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(nav.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        tableView.tableFooterView = UIView()
        tableView.tableHeaderView = contentView
        tableView.contentInsetAdjustmentBehavior = .never
        contentView.snp.makeConstraints { make in
            make.width.height.equalToSuperview() // 确保 contentView 宽度与父视图一致
        }
        tableView.delegate = self
        contentView.addSubview(mineGoldView)
        mineGoldView.button.isHidden = true
        mineGoldView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(98)
        }
        
        contentView.addSubview(selectGoldView)
        let height = 80.5 * 3 + 10.5 * 2 + 13 * 2
        selectGoldView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(mineGoldView.snp.bottom)
            make.height.equalTo(height)
        }
        selectGoldView.selectedAction = {
            [weak self] in
            self?.inputGoldCountView.textField.text = ""
            self?.inputGoldCountView.textField.resignFirstResponder()
        }
        
        contentView.addSubview(inputGoldCountView)
        inputGoldCountView.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(18)
            make.top.equalTo(selectGoldView.snp.bottom)
            make.height.equalTo(53)
        }
        inputGoldCountView.beginEditing = {
            [weak self] in
            self?.selectGoldView.selectIndex = -1
        }
        
        contentView.addSubview(tipTitleLabel)
        contentView.addSubview(tipContentLabel)
        
        tipTitleLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().inset(18)
            make.top.equalTo(inputGoldCountView.snp.bottom).offset(12)
        }
        
        tipContentLabel.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(18)
            make.top.equalTo(tipTitleLabel.snp.bottom).offset(8)
        }
        
        view.addSubview(button)
        button.snp.makeConstraints { make in
            make.left.right.equalToSuperview().inset(46.5)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-24)
            make.height.equalTo(52)
        }
        print(contentView.isUserInteractionEnabled)
        print(contentView.superview?.isUserInteractionEnabled ?? "No superview")  
    }
}
extension AddGoldViewController: UITableViewDelegate{
//    func scrollViewDidScroll(_ scrollView: UIScrollView) {
//        inputGoldCountView.textField.resignFirstResponder()
//    }
}
